#!/usr/bin/php
<?php

/*

Released under Public Domain. Feel Free to modify and use it.

*/

mb_language('uni');
mb_internal_encoding('UTF-8');
require("class.phpmailer.php");

@mysql_connect("localhost","sqlusername","sqlpassword");
$dbselect = @mysql_select_db("asterisktable");

$voicemaildir = "/var/spool/asterisk/voicemail/" . $argv[1] . "/";
$sfilename = sprintf($voicemaildir . "%s/INBOX/msg%04d.wav",$argv[2],$argv[3]-1);
$dfilename = sprintf($voicemaildir . "%s/INBOX/msg%04d.mp3",$argv[2],$argv[3]-1);
$infofilename = sprintf($voicemaildir . "%s/INBOX/msg%04d.txt",$argv[2],$argv[3]-1);
system("lame -V2  $sfilename $dfilename");

$stmt = sprintf("Select * from voicemail_users where mailbox='%s' and context='%s'",$argv[2],$argv[1]);
$result = mysql_query($stmt);
if( mysql_num_rows($result) == 0 ) 
{
	exit;
}

$row = mysql_fetch_assoc($result);
$rcptemail = $row['email'];
$rcptname = $row['fullname'];

$msginfo = parse_ini_file($infofilename);


$mail = new PHPMailer();

$mail->From = "noreply@voicetoemail.com";
$mail->FromName = "VoicetoEmail";
$mail->AddAddress($rcptemail, $rcptname);
$mail->AddReplyTo("noreply@voicetoemail.com", "VoicetoEmail");

$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->AddAttachment($dfilename);         // add attachments
$mail->IsHTML(true);                                  // set email format to HTML


$mail->Subject = "Voicemail from  " . $msginfo['callerid'];
$mail->Body    = "Dear " . $rcptname . ",\n<br><br>Attached is the voice received from " . $msginfo['callerid'] . "\n<br>Date & Time:"  . $msginfo['origdate'] . "\n\n<br><br>Support,<br>\nhttp://www.CalltoEmail.com";
$mail->AltBody = $mail->Body;

$mail->Send();

system("rm -rf $sfilename");
system("rm -rf $dfilename");
system("rm -rf $infofilename");


?>
